package files

import (
	"fmt"
	"path/filepath"
	"strings"
	"time"
)

// 文件扩展名分类
var (
	imageExts = map[string]bool{
		".jpg": true, ".jpeg": true, ".png": true, ".gif": true,
		".bmp": true, ".webp": true, ".svg": true, ".ico": true,
	}

	documentExts = map[string]bool{
		".pdf": true, ".doc": true, ".docx": true, ".xls": true,
		".xlsx": true, ".ppt": true, ".pptx": true, ".txt": true,
		".rtf": true,
	}

	audioExts = map[string]bool{
		".mp3": true, ".wav": true, ".flac": true, ".aac": true,
		".ogg": true, ".m4a": true,
	}

	videoExts = map[string]bool{
		".mp4": true, ".avi": true, ".mkv": true, ".mov": true,
		".wmv": true, ".flv": true, ".webm": true,
	}

	archiveExts = map[string]bool{
		".zip": true, ".rar": true, ".7z": true, ".tar": true,
		".gz": true, ".bz2": true,
	}

	codeExts = map[string]bool{
		".go": true, ".js": true, ".ts": true, ".py": true,
		".java": true, ".cpp": true, ".c": true, ".h": true,
		".css": true, ".html": true, ".xml": true, ".json": true,
		".yaml": true, ".yml": true,
	}
)

// Classify 返回兼容旧接口的分类结果。
func Classify(fileName string) string {
	return ClassifyFile(fileName)
}

// ClassifyFile 根据文件扩展名对文件进行分类。
func ClassifyFile(filename string) string {
	ext := strings.ToLower(filepath.Ext(filename))

	switch {
	case imageExts[ext]:
		return "images"
	case documentExts[ext]:
		return "documents"
	case audioExts[ext]:
		return "audio"
	case videoExts[ext]:
		return "videos"
	case archiveExts[ext]:
		return "archives"
	case codeExts[ext]:
		return "code"
	default:
		return "others"
	}
}

// GenerateRemotePath 根据本地文件路径和当前目录生成带时间戳的远程路径。
func GenerateRemotePath(localPath, currentDir string) string {
	filename := filepath.Base(localPath)
	baseName := strings.TrimSuffix(filename, filepath.Ext(filename))
	if baseName == "" {
		baseName = filename
	}

	timestamp := time.Now().Format("20060102-150405")
	newFileName := fmt.Sprintf("%s-%s%s", baseName, timestamp, filepath.Ext(filename))

	targetDir := strings.Trim(strings.TrimSpace(currentDir), "/")
	if targetDir == "" {
		targetDir = ClassifyFile(filename)
	}

	return fmt.Sprintf("%s/%s", targetDir, newFileName)
}
